import { http } from "@/utils/http";
// import { getToken } from "@/utils/auth";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

// 为task API添加Authorization头的辅助函数
const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// GET请求辅助函数（使用params而不是data）
const taskRequestGet = <T>(url: string, params?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>("get", url, {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};

/** 获取资产列表 */
export const getAssetList = ({
  data,
  type = "asset",
}: {
  data: object;
  type: string;
}) => {
  return taskRequest<Result>("post", `/api/api/${type}/data`, data);
};

// ============ 漏洞情报模块 API ============

// 🎯 仪表板数据接口（根据MD文档设计）

// 1. 获取统计概览
export const getIntelligenceStatisticsOverview = (params?: {
  days?: number;
}) => {
  return taskRequestGet<Result>(
    "/api/intelligence/statistics/overview",
    params
  );
};

// 2. 获取情报趋势数据（包含折线图和饼图数据）
export const getIntelligenceTrend = (params?: { days?: number }) => {
  return taskRequest<Result>(
    "post",
    "/api/intelligence/dashboard/trend",
    params
  );
};

// 4. 获取最新高危情报
export const getLatestHighRiskIntelligence = (params?: { limit?: number }) => {
  return taskRequestGet<Result>("/api/intelligence/latest/high_risk", params);
};

// 5. 获取待处理任务统计
export const getPendingTasks = () => {
  return taskRequestGet<Result>("/api/intelligence/dashboard/pending_tasks");
};

// 2. 获取情报状态（根据MD文档设计）
export const getIntelligenceStatus = () => {
  return taskRequestGet<Result>("/api/intelligence/status");
};

// 3. 获取工作流统计（根据MD文档设计，Dashboard使用）
export const getIntelligenceWorkflowStatistics = () => {
  return taskRequestGet<Result>("/api/intelligence/workflow/statistics");
};

// 查询工作流历史（根据MD文档设计，Workflow组件使用）
export const getWorkflowHistory = (params?: {
  workflow_type?: string; // batch 或 continuous
  status?: string; // completed、failed、stopped
  start_date?: string; // YYYY-MM-DD
  end_date?: string; // YYYY-MM-DD
  page?: number; // 页码，默认1
  page_size?: number; // 每页数量，默认20，最大值100
}) => {
  return taskRequestGet<Result>("/api/intelligence/workflow/history", params);
};

// 情报仪表板（保留兼容性）
export const getIntelligenceDashboard = (params?: {
  dashboard_type?: string;
  refresh_cache?: boolean;
}) => {
  return taskRequestGet<Result>("/api/intelligence/dashboard", params);
};

// 统计信息（保留兼容性）
export const getIntelligenceStatistics = (params?: {
  time_range?: string;
  include_details?: boolean;
}) => {
  return taskRequestGet<Result>("/api/intelligence/statistics", params);
};

// ============ 情报管理 API ============

// 4. 获取情报历史列表（🆕 已优化版本，根据MD文档设计）
export const getIntelligenceHistory = (data?: {
  page?: number;
  page_size?: number;
  search_keyword?: string; // 🔥 新功能：关键词搜索（情报名称、CVE ID、描述）
  severity?: string; // 严重程度筛选
  has_matched_assets?: boolean | null; // 🔥 新功能：资产匹配筛选 (true/false/null)
  time_filter?: string; // 🔥 新功能：快速时间筛选 (last_7_days/last_30_days/this_month/this_quarter/this_year)
  date_range?: {
    start_date?: string;
    end_date?: string;
  }; // 🔥 新功能：精确时间范围
  source?: string;
  has_poc?: boolean;
  sort_by?: string;
  sort_order?: string;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/history", data);
};

// 5. 获取情报详情（根据MD文档设计）
export const getIntelligenceDetail = (data: { intelligence_id: string }) => {
  return taskRequest<Result>("post", "/api/intelligence/detail", data);
};

// 6. 强制触发情报收集（根据MD文档设计）
export const forceIntelligenceCollection = (data?: {
  source?: string;
  force?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/force", data);
};

// 7. 测试情报源连接（根据MD文档设计）
export const testIntelligenceSource = (data: {
  source_id: string;
  connection_config?: any;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/test", data);
};

// 8. 获取情报源配置（根据MD文档设计）
export const getIntelligenceSources = () => {
  return taskRequestGet<Result>("/api/intelligence/sources");
};

// 保留旧接口名称以兼容（使用新接口）
export const getIntelligenceList = getIntelligenceHistory;
export const getIntelligenceDetails = getIntelligenceDetail;

// 情报数据上传
export const uploadIntelligence = (data: {
  source: string;
  intelligence_data: Array<{
    vul_name: string;
    vul_id: string;
    vul_level?: string;
    description?: string;
    cve_id?: string;
    cvss_score?: number;
    published_date?: string;
    affected_products?: string;
    keywords?: {
      product_name?: string;
      service_type?: string;
      version_info?: string;
    };
    has_poc?: boolean;
    has_exploit?: boolean;
  }>;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/upload", data);
};

// 情报匹配执行
export const matchIntelligence = (data: {
  intelligence_ids: number[]; // 必填：情报ID列表
  match_all_assets?: boolean; // 可选：预留参数
}) => {
  return taskRequest<Result>("post", "/api/intelligence/match", data);
};

// POC推荐分析
export const recommendPocs = (data: {
  intelligence_id: string;
  recommendation_mode?: string;
  min_score?: number;
  max_results?: number;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/recommend_pocs", data);
};

// ============ 工作流管理 API ============

// 9. 启动工作流（根据MD文档设计）
export const startWorkflow = (data: {
  type: string; // continuous/batch/verification
  force_rescan?: boolean;
  intelligence_ids?: number[]; // 批量处理时需要
}) => {
  return taskRequest<Result>("post", "/api/intelligence/workflow/start", data);
};

// 10. 停止工作流（根据MD文档设计）
export const stopWorkflow = (data: {
  workflow_id?: string; // 可选，如果不提供则停止所有
  workflow_type?: string; // continuous/batch/verification
}) => {
  return taskRequest<Result>("post", "/api/intelligence/workflow/stop", data);
};

// 11. 查询工作流状态（根据MD文档设计，GET请求）
export const getWorkflowStatus = (params?: {
  workflow_id?: string;
  workflow_type?: string;
}) => {
  return taskRequestGet<Result>("/api/intelligence/workflow/status", params);
};

// 12. 查询工作流历史（已在仪表板接口中定义，使用 getWorkflowHistory）

// ============ 验证复核 API ============

// 17. 创建验证任务（根据MD文档设计）
export const createVerificationTask = (data: {
  task_name: string;
  intelligence_id: number;
  target_assets: Array<{
    ip: string;
    port?: number;
    service?: string;
  }>;
  poc_ids?: number[];
  priority?: string; // high/medium/low
  verification_config?: {
    timeout?: number;
    retry_count?: number;
    auto_report?: boolean;
  };
}) => {
  return taskRequest<Result>(
    "post",
    "/api/intelligence/verification/create",
    data
  );
};

// 18. 获取验证历史（根据MD文档设计）
export const getVerificationHistory = (params?: {
  limit?: number;
  status?: string; // pending/running/completed/failed
  page?: number;
  page_size?: number;
}) => {
  return taskRequestGet<Result>(
    "/api/intelligence/verification/history",
    params
  );
};

// ============ 资产关联分析 API ============

// 19. 资产统计信息（根据MD文档设计）
export const getAssetStatistics = (data?: {
  time_range?: string;
  include_details?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/asset/statistics", data);
};

// 20. 查询匹配资产（根据MD文档设计）
export const queryMatchedAssets = (data?: {
  intelligence_id?: number;
  ip_range?: string;
  service_type?: string;
  risk_level?: string;
  page?: number;
  per_page?: number;
}) => {
  return taskRequest<Result>("post", "/api/asset/enhanced_query", data);
};

// 资产关联分析（保留兼容性，已废弃）
export const assetsCorrelation = (data: {
  analysis_config: {
    analysis_mode: string;
    correlation_type?: string;
    min_confidence_score?: number;
    time_range_days?: number;
  };
  scope_filter?: {
    asset_groups?: string[];
    intelligence_sources?: string[];
    severity_levels?: string[];
  };
}) => {
  return taskRequest<Result>(
    "post",
    "/api/intelligence/assets/correlation",
    data
  );
};

// 处理日志查询
export const getProcessingLogs = (data?: {
  query_config?: {
    log_level?: string;
    operation_type?: string;
    time_range?: {
      start_time?: string;
      end_time?: string;
    };
    keyword?: string;
  };
  pagination?: {
    page?: number;
    page_size?: number;
  };
  sort_config?: {
    sort_by?: string;
    sort_order?: string;
  };
}) => {
  return taskRequest<Result>("post", "/api/intelligence/logs/processing", data);
};

// ============ 调度器配置 API ============

// 1.2.1 获取调度器状态
export const getSchedulerStatus = () => {
  return taskRequestGet<Result>("/api/intelligence/scheduler/status");
};

// 1.2.2 获取调度器配置
export const getSchedulerConfig = () => {
  return taskRequestGet<Result>("/api/intelligence/config");
};

// 1.2.3 更新调度器配置（自动热重载）
export const updateSchedulerConfig = (data: {
  action: string;
  config: Record<string, string>;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/config", data);
};

// 1.2.4 暂停调度器
export const pauseScheduler = () => {
  return taskRequest<Result>("post", "/api/intelligence/scheduler/pause", {});
};

// 1.2.4 恢复调度器
export const resumeScheduler = () => {
  return taskRequest<Result>("post", "/api/intelligence/scheduler/resume", {});
};

// 1.2.5 手动触发任务
export const triggerSchedulerTask = (data?: {
  task_type?: string;
  job_id?: string;
}) => {
  return taskRequest<Result>(
    "post",
    "/api/intelligence/scheduler/trigger",
    data || {}
  );
};

// ============ 漏洞复核 API ============

// 2.2.1 获取复核列表
export const getReviewList = (data?: {
  page?: number;
  page_size?: number;
  status?: string; // pending/in_review/approved/rejected/all
  asset_id?: string;
  severity?: string; // critical/high/medium/low
  keyword?: string;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/review/pending", data);
};

// 2.2.2 获取复核详情
export const getReviewDetail = (matchId: string) => {
  return taskRequestGet<Result>(`/api/intelligence/review/detail/${matchId}`);
};

// 2.2.3 提交复核
export const submitReview = (data: any) => {
  return taskRequest<Result>("post", "/api/intelligence/review/submit", data);
};

// 2.2.4 批量复核
export const batchReview = (data: {
  match_ids: string[];
  decision: string; // approved/rejected/ignored
  comment?: string;
  auto_scan?: boolean;
}) => {
  return taskRequest<Result>("post", "/api/intelligence/review/batch", data);
};

// 2.2.5 获取扫描进度
export const getScanProgress = (scanId: string) => {
  return taskRequestGet<Result>(
    `/api/intelligence/review/scan/progress/${scanId}`
  );
};

// 2.2.6 获取扫描报告
export const getScanReport = (scanId: string) => {
  return taskRequestGet<Result>(
    `/api/intelligence/review/scan/report/${scanId}`
  );
};

// 2.3 获取复核统计
export const getReviewStatistics = () => {
  return taskRequestGet<Result>("/api/intelligence/review/statistics");
};

// ============ 漏洞管理 API ============

/** 获取漏洞列表 */
export const getVulnerabilityList = (params?: {
  page?: number;
  page_size?: number;
  severity?: string; // critical | high | medium | low | info | unknown
  has_cve?: boolean;
  tags?: string; // 逗号分隔
  keyword?: string;
  is_active?: boolean;
}) => {
  return taskRequestGet<Result>("/api/vulnerability/list", params);
};

/** 获取漏洞详情 */
export const getVulnerabilityDetail = (id: number) => {
  return taskRequestGet<Result>(`/api/vulnerability/detail/${id}`);
};

/** 上传POC ZIP文件 */
export const uploadPocZip = (formData: FormData) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/poc/upload_zip", {
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

/** 导入漏洞库Excel */
export const uploadVulnerabilityExcel = (formData: FormData) => {
  const token = getToken175();
  return http.request<Result>("post", "/api/vulnerability/upload_excel", {
    data: formData,
    headers: {
      "Content-Type": "multipart/form-data",
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ============ 漏洞扫描测试 API ============

/** 创建扫描任务 */
export const createVulnerabilityScan = (data: any) => {
  return taskRequest<Result>("post", "/api/asset/vulnerability/scan", data);
};

/** 查询扫描状态 */
export const getVulnerabilityScanStatus = (taskId: string) => {
  return taskRequest<Result>(
    "post",
    `/api/asset/vulnerability/scan_status/${taskId}`,
    {}
  );
};

/** 获取扫描结果 */
export const getVulnerabilityScanResult = (taskId: string) => {
  return taskRequest<Result>(
    "post",
    `/api/asset/vulnerability/scan_result/${taskId}`,
    {}
  );
};
